package com.simple.util;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZIPUtil {


    public static void zip (List<Map<String,Object>> data, String imgPath, HttpServletResponse response,String type){
        try {
            String downloadFilename = URLEncoder.encode("img_"+ type +".zip", "UTF-8");
            response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

            for(Map<String,Object> map : data){
                String img_name = (String)map.get("img_name");

                String file = imgPath + img_name;
                zos.putNextEntry(new ZipEntry("img" + File.separator + img_name));
                InputStream fis = new FileInputStream(new File(file));
                byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
                fis.close();
            }
            zos.flush();
            zos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
